<template>
  <div class="app-container">
    <div class="mb-20">
      <el-button
        class="btn-active"
        icon="el-icon-plus"
        size="mini"
        @click="goAdd"
        >新增角色</el-button
      >
      <el-button
        class="btn-delete"
        icon="el-icon-delete"
        size="mini"
        @click="deleteRow"
        >删除</el-button
      >
    </div>
    <div class="search">
      <el-form ref="form" :model="form" label-width="80px" inline>
        <el-form-item label="">
          <el-date-picker
            v-model="form.createTime"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="创建时间"
          />
        </el-form-item>
        <el-form-item label="">
          <el-input v-model="form.createBy" placeholder="创建人员" />
        </el-form-item>
        <el-form-item label="">
          <el-input v-model="form.roleName" placeholder="角色名称" />
        </el-form-item>
        <el-form-item label="">
          <el-button size="mini" icon="el-icon-search" @click="search"
            >查询</el-button
          >
          <el-button size="mini" icon="el-icon-refresh-right" @click="search(1)"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      element-loading-text="加载中"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column align="center" label="序号" width="95">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="角色名称">
        <template slot-scope="scope">
          {{ scope.row.roleName }}
        </template>
      </el-table-column>
      <el-table-column label="权限字符" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.roleKey }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色顺序" align="center">
        <template slot-scope="scope">
          {{ scope.row.roleSort }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.status == 1" class="green-tag">未启用</span>
          <span v-if="scope.row.status == 0" class="other-tag">启用</span>
        </template>
      </el-table-column>
      <el-table-column class-name="备注" label="备注" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="created_at"
        label="操作"
        width="240"
      >
        <template slot-scope="scope">
          <el-button
            class="detail"
            icon="el-icon-edit-outline"
            @click="goEdit(scope.row)"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog
      title="添加用户"
      :visible.sync="dialogFormVisible"
      :modal="false"
      width="800px"
    >
      <el-form ref="dialogForm" :model="dialogForm">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item
              label="角色名称"
              prop="roleName"
              :rules="{
                required: true,
                message: '角色名称不能为空',
                trigger: 'blur',
              }"
            >
              <el-input v-model="dialogForm.roleName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="权限字符"
              prop="roleKey"
              :rules="{
                required: true,
                message: '权限字符不能为空',
                trigger: 'blur',
              }"
            >
              <el-input v-model="dialogForm.roleKey" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="角色顺序">
              <el-input v-model="dialogForm.roleSort" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="菜单权限">
              <div class="el-input">
                <el-tree
                  ref="menu"
                  class="tree-border"
                  :data="menuOptions"
                  show-checkbox
                  node-key="menuId"
                  :props="defaultProps"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态">
              <div class="el-input">
                <el-radio-group v-model="dialogForm.status" size="small">
                  <el-radio :label="0">启用</el-radio>
                  <el-radio :label="1">未启用</el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注">
              <el-input v-model="dialogForm.remark" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="center">
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button class="cancel" @click="dialogFormVisible = false"
          >取消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { menuList, roleList } from "@/api/table";
import { removeRole, roleAdd, roleEdit, userResetPwd } from "@/api/form";
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      menuOptions: [],
      defaultProps: {
        children: "children",
        label: "menuName",
      },
      dialogFormVisible: false,
      dialogForm: {
        status: 0,
      },
      currentPage: 1,
      pageNum: 10,
      total: 0,
      multipleSelection: [],
      form: {},
      list: null,
      options: [],
      listLoading: true,
    };
  },
  created() {
    roleList().then((res) => {
      console.log(res);
      this.options = res.rows;
    });
    this.init();
    this.fetchData();
  },
  methods: {
    init() {
      menuList({
        pageSize: 1,
        pageNum: 1000,
      }).then((res) => {
        console.log(res);
        this.menuOptions = res;
      });
    },
    goEdit(row) {
      this.dialogFormVisible = true;
      row.status = Number(row.status);
      this.dialogForm = JSON.parse(JSON.stringify(row));

      if (row.menuIds) {
        setTimeout(() => {
          const checkedKeys = row.menuIds;
          console.log(row);
          this.$refs.menu.setCheckedKeys([]);
          checkedKeys.forEach((v) => {
            this.$nextTick(() => {
              this.$refs.menu.setChecked(v, true, false);
            });
          });
        }, 1000);
      } else {
        this.$refs.menu.setCheckedKeys([]);
      }
    },
    search(num) {
      if (num == 1) {
        this.form = {};
      }
      this.currentPage = 1;
      this.fetchData();
    },
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      const halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    submit() {
      this.$refs["dialogForm"].validate((valid) => {
        if (valid) {
          this.dialogForm.menuIds = this.getMenuAllCheckedKeys();
          if (this.dialogForm.roleId) {
            roleEdit(this.dialogForm).then((res) => {
              if (res.code == 200) {
                this.$message.success("操作成功");
                this.dialogFormVisible = false;
                this.fetchData();
              }
            });
          } else {
            this.dialogForm.menuIds = this.getMenuAllCheckedKeys();
            roleAdd(this.dialogForm).then((res) => {
              if (res.code == 200) {
                this.$message.success("操作成功");
                this.dialogFormVisible = false;
                this.fetchData();
              }
            });
          }
        }
      });
    },
    deleteRow() {
      removeRole({
        ids: this.multipleSelection.map((item) => item.roleId).join(","),
      }).then((res) => {
        if (res.code == 200) {
          this.$message.success("操作成功");
          this.fetchData();
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.pageNum = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    goAdd() {
      this.dialogForm = { status: 0 };
      this.dialogFormVisible = true;
      this.$refs.menu.setCheckedKeys([]);
    },
    fetchData() {
      this.listLoading = true;
      roleList({
        pageSize: this.pageNum,
        pageNum: this.currentPage,
        ...this.form,
      }).then((res) => {
        this.list = res.rows;
        this.listLoading = false;
        this.total = res.total;
      });
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep {
  .el-tree {
    background: transparent;
    color: #fff;
    .el-tree-node__content:hover,
    .el-tree-node:focus > .el-tree-node__content {
      background: transparent;
      color: #fff;
    }
  }
}
::v-deep {
  .detail.el-button {
    padding: 9px 4px;
  }
}
::v-deep {
  .v-modal {
    background: none;
  }
}
::v-deep {
  .el-dialog {
    color: white;
    background: rgb(3, 28, 43);
    .el-dialog__title,
    .el-form-item__label {
      color: white;
    }
  }
}
</style>
